package com.shenmazg6.chatroom.chat;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 军哥
 * @version 1.0
 * @description: UserWebSocket
 * @date 2022/12/27 14:33
 */

@Component
@Slf4j
@ServerEndpoint(value = "/chatRoom/{userId}")
public class UserWebSocket {

    // 当前对象的session
    private Session _session;

    // 当前用户ID
    private Integer userId;

    // 所有用户的列表
    private static Map<String, Session> userSessions = new ConcurrentHashMap<>();

    /**
     * 当连接建立成功时被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")Integer userId) {
        userSessions.put(session.getId(), session);
        this._session = session;
        this.userId = userId;
        log.info("onOpen,在线人数为："+ userSessions.size());

        // 发送通知
        sendAllMessage("有新的小朋友【进来】了");

    }

    /**
     * 当连接端口时被调用
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId")Integer userId) {
        userSessions.remove(session.getId());
        this._session = null;
        this.userId = null;

        log.info("onClose,在线人数为："+ userSessions.size());


        // 发送通知
        sendAllMessage("有小朋友【离开】了");

    }

    /**
     * 当有消息到达时被调用
     * @param message
     * @param session
     */

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId")Integer userId) {
        log.info("onMessage:："+ message);

        // 发送消息
        sendAllMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId")Integer userId) {
        userSessions.remove(session.getId());
        this._session = null;
        this.userId = null;
        log.info("onError,在线人数为："+ userSessions.size());


        // 发送通知
        sendAllMessage("有小朋友网络问题【离开】了");
    }

    /**
     * 主动发送消息
     * @param session
     * @param message
     * @throws IOException
     */
    public void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    public void sendAllMessage(String message) {
        userSessions.keySet().forEach(item -> {
            Session session = userSessions.get(item);

            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        });
    }
}
